<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>前端响应式网站设计 | Lemonxu's Blog</title><meta name="author" content="Lemonxu"><meta name="copyright" content="Lemonxu"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="前端响应式网站设计，适应不同屏幕像素、视口大小变化。">
<meta property="og:type" content="article">
<meta property="og:title" content="前端响应式网站设计">
<meta property="og:url" content="https://lemonxu.eu.org/2023/05/31/responsive-html/responsive-html/index.html">
<meta property="og:site_name" content="Lemonxu&#39;s Blog">
<meta property="og:description" content="前端响应式网站设计，适应不同屏幕像素、视口大小变化。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://lemonxu.eu.org/images/bg/641.jpg">
<meta property="article:published_time" content="2023-05-31T01:07:50.000Z">
<meta property="article:modified_time" content="2023-06-13T01:18:40.525Z">
<meta property="article:author" content="Lemonxu">
<meta property="article:tag" content="前端响应式">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://lemonxu.eu.org/images/bg/641.jpg"><link rel="shortcut icon" href="/blog/images/favicon-32x32-next.png"><link rel="canonical" href="https://lemonxu.eu.org/2023/05/31/responsive-html/responsive-html/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//hm.baidu.com"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta name="baidu-site-verification" content="codeva-aqnyzLi7SQ"/><meta name="msvalidate.01" content="2A101DE4CB69400C01A80B1A89A62400"/><link rel="stylesheet" href="/blog/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.min.css" media="print" onload="this.media='all'"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?86df0317d9503122cab4c4dc5e8dcb55";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><script>const GLOBAL_CONFIG = {
  root: '/blog/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":200},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: true,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '前端响应式网站设计',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-06-13 09:18:40'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/blog/images/user.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">4</div></a><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">4</div></a><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">8</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/blog/link/"><i class="fa-fw fas fa-link"></i><span> 友情链接</span></a></div><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/blog/images/bg/641.jpg')"><nav id="nav"><span id="blog-info"><a href="/blog/" title="Lemonxu's Blog"><span class="site-name">Lemonxu's Blog</span></a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/blog/link/"><i class="fa-fw fas fa-link"></i><span> 友情链接</span></a></div><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);" rel="external nofollow noreferrer"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">前端响应式网站设计</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-05-31T01:07:50.000Z" title="发表于 2023-05-31 09:07:50">2023-05-31</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-06-13T01:18:40.525Z" title="更新于 2023-06-13 09:18:40">2023-06-13</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/%E5%89%8D%E7%AB%AF%E5%93%8D%E5%BA%94%E5%BC%8F/">前端响应式</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/%E5%89%8D%E7%AB%AF%E5%93%8D%E5%BA%94%E5%BC%8F/HTML/">HTML</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/%E5%89%8D%E7%AB%AF%E5%93%8D%E5%BA%94%E5%BC%8F/HTML/CSS/">CSS</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">5.1k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>17分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="前端响应式网站设计"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="为什么需要设计响应式设计"><a href="#为什么需要设计响应式设计" class="headerlink" title="为什么需要设计响应式设计"></a>为什么需要设计响应式设计</h1><p>响应式设计就是为了为了统一所有设备，给用户展示最优的交互界面。</p>
<ul>
<li>即便是PC或Mac用户，有查显示只有一半的人会将浏览器全屏显示，而剩下的一般人使用多大的浏览器，很难预知；</li>
<li>台式机、投影、电视、笔记本、手机、平板、手表、VR……智能设备正在不断增加，“主流设备”的概念正在消失；</li>
<li>屏幕分辨率正飞速发展，同一张图片在不同设备上看起来，大小可能天差地别；</li>
<li>鼠标、触屏、笔、摄像头手势……不可预期的操控方式正在不断出现。</li>
</ul>
<span id="more"></span>


<p>响应式设计就是RWD（Responsive Web Design），与此目标比较相似的另一个设计就是 自适应网页设计AWD（Adaptive Web Design）。</p>
<p><strong>相同点</strong>：<br>两者的目标相同，都是针对不同的分辨率&#x2F;device采用不同的样式和布局达到页面展示最优；<br>在布局方式本质没有差别（AWD 也 including responsive layout）。</p>
<p><strong>差别点</strong>:<br>RWD强调一套页面进行多端兼容展示（桌机、平板、手机都是用同一个 HTML 代码和同一个 CSS 文档，能依照不同屏幕宽度的条件，来改变排版），而AWD给出多套页面，对于不同device进行了分类处理（在不同的装置开启网页时，AWD 会先判定装置屏幕尺寸是哪一种，来读取不同的 CSS 文档，呈现网页设计排版）；<br>RWD使用流动网格、CSS、以及灵活的基础可能需要更多的代码和实施策略（「媒体设备查询 @media」是 CSS 重要的能力之一，透过它可分辨开启网页的浏览器宽度大小，实时读取不同的样式呈现，就能达成 RWD 响应式效果），而AWD一般是server side detection，一次性渲染既定布局和样式。</p>
<h1 id="响应式设计实现方案"><a href="#响应式设计实现方案" class="headerlink" title="响应式设计实现方案"></a>响应式设计实现方案</h1><p>主要从响应式布局（媒体查询、流式布局）、相对单位、响应式文字、响应式图片几个方面来进行响应式设计实现。</p>
<h2 id="页面布局"><a href="#页面布局" class="headerlink" title="页面布局"></a>页面布局</h2><p>页面布局目前有：静态布局、流式布局、自适应布局、响应式布局、弹性布局（rem&#x2F;em布局）。<br>简单介绍下：</p>
<h3 id="静态布局"><a href="#静态布局" class="headerlink" title="静态布局"></a><strong>静态布局</strong></h3><p>即传统Web设计，网页上所有元素的尺寸一律使用px作为单位；设置了最小宽度，小于这个宽度就会出现滚动条，如果大于这个宽度则内容居中外加背景，常见于PC端。</p>
<blockquote>
<p><strong>设计方法</strong>：<br>PC：居中布局，所有样式使用绝对宽度&#x2F;高度(px)，设计一个Layout，在屏幕宽高有调整时，使用横向和竖向的滚动条来查阅被遮掩部分；</p>
<p>移动设备：另外建立移动网站，单独设计一个布局，使用不同的域名如wap.或m.。</p>
<p>在移动端开发中采用静态布局的两种方式：</p>
<p>（1）在viewport meta标签上设置width&#x3D;320，页面的各个元素也采用px作为单位。通过用JS动态修改标签的initial-scale使得页面等比缩放，从而刚好占满整个屏幕。</p>
<p>（2）设在viewport meta标签上设置content”width&#x3D;640,user-scalable&#x3D;no，页面的各个元素也采用px作为单位。由于640px超出了手机宽度，浏览器会自动缩小页面至刚好全屏。</p>
<p>优点：这种布局方式对设计师和CSS编写者来说都是最简单的，亦没有兼容性问题。缺点：显而易见，即不能根据用户的屏幕尺寸做出不同的表现。</p>
</blockquote>
<h3 id="流式布局"><a href="#流式布局" class="headerlink" title="流式布局"></a><strong>流式布局</strong></h3><p> 是页面元素的宽度按照屏幕分辨率进行适配调整，但整体布局不变。代表作栅栏系统（网格系统）。</p>
<p>网页中主要的划分区域的尺寸使用百分数（搭配min-*、max-*属性使用），例如，设置网页主体的宽度为80%，min-width为960px。图片也作类似处理（width:100%, max-width一般设定为图片本身的尺寸，防止被拉伸而失真）。</p>
<p>布局特点：屏幕分辨率变化时，页面里元素的大小会变化而但布局不变。【这就导致如果屏幕太大或者太小都会导致元素无法正常显示】</p>
<blockquote>
<p><strong>分类</strong></p>
<ul>
<li>左侧固定，右侧自适应</li>
<li>右侧固定，左侧自适应</li>
<li>两侧固定，中间自适应（圣杯布局）</li>
<li>等分布</li>
</ul>
<p><strong>设计方法：</strong></p>
<p>使用%百分比定义宽度，高度大都是用px来固定住，可以根据可视区域 (viewport) 和父元素的实时尺寸进行调整，尽可能的适应各种分辨率。往往配合 max-width&#x2F;min-width 等属性控制尺寸流动范围以免过大或者过小影响阅读。</p>
</blockquote>
<p>这种布局方式在Web前端开发的早期历史上，用来应对不同尺寸的PC屏幕（那时屏幕尺寸的差异不会太大），在当今的移动端开发也是常用布局方式，但缺点明显：主要的问题是如果屏幕尺度跨度太大，那么在相对其原始设计而言过小或过大的屏幕上不能正常显示。因为宽度使用%百分比定义，但是高度和文字大小等大都是用px来固定，所以在大屏幕的手机下显示效果会变成有些页面元素宽度被拉的很长，但是高度、文字大小还是和原来一样（即，这些东西无法变得“流式”），显示非常不协调。</p>
<h3 id="自适应布局"><a href="#自适应布局" class="headerlink" title="自适应布局"></a><strong>自适应布局</strong></h3><p>自适应布局的特点是分别为不同的屏幕分辨率定义布局，即创建多个静态布局，每个静态布局对应一个屏幕分辨率范围。改变屏幕分辨率可以切换不同的静态局部（页面元素位置发生改变），但在每个静态布局中，页面元素不随窗口大小的调整发生变化。可以把自适应布局看作是静态布局的一个系列。</p>
<p>布局特点：屏幕分辨率变化时，页面里面元素的位置会变化而大小不会变化。</p>
<blockquote>
<p><strong>设计方法</strong>：使用 @media 媒体查询给不同尺寸和介质的设备切换不同的样式。在优秀的响应范围设计下可以给适配范围内的设备最好的体验，在同一个设备下实际还是固定的布局。</p>
</blockquote>
<h3 id="响应式布局"><a href="#响应式布局" class="headerlink" title="响应式布局"></a><strong>响应式布局</strong></h3><p>随着CSS3出现了<strong>媒体查询</strong>技术，又出现了<strong>响应式设计</strong>的概念。响应式设计的目标是确保一个页面在所有终端上（各种尺寸的PC、手机、手表、冰箱的Web浏览器等等）都能显示出令人满意的效果，对CSS编写者而言，在实现上不拘泥于具体手法，但通常是糅合了流式布局+弹性布局，再搭配媒体查询技术使用。——分别为不同的屏幕分辨率定义布局，同时，在每个布局中，应用流式布局的理念，即页面元素宽度随着窗口调整而自动适配。即：创建多个流体式布局，分别对应一个屏幕分辨率范围。可以把响应式布局看作是流式布局和自适应布局设计理念的融合。响应式几乎已经成为优秀页面布局的标准。</p>
<p>布局特点：每个屏幕分辨率下面会有一个布局样式，即元素位置和大小都会变。</p>
<blockquote>
<p><strong>设计方法</strong>：媒体查询+流式布局。通常使用 @media 媒体查询 和网格系统 (Grid System) 配合相对布局单位进行布局，实际上就是综合响应式、流动等上述技术通过 CSS 给单一网页不同设备返回不同样式的技术统称。</p>
</blockquote>
<p>优点：适应pc和移动端，如果足够耐心，效果完美;优点：适应pc和移动端，如果足够耐心，效果完美。</p>
<p>响应式页面在头部会加上这一段代码：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">&quot;applicable-device&quot;</span> <span class="attr">content</span>=<span class="string">&quot;pc,mobile&quot;</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">&quot;Cache-Control&quot;</span> <span class="attr">content</span>=<span class="string">&quot;no-transform &quot;</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h4 id="媒体查询"><a href="#媒体查询" class="headerlink" title="媒体查询"></a>媒体查询</h4><p>CSS3媒体查询可以让我们针对不同的媒体类型定义不同的样式，当重置浏览器窗口大小的过程中，页面也会根据浏览器的宽度和高度重新渲染页面。</p>
<p>在进行媒体查询实现前，需要考虑如何合理地选定分割点，可以根据你的设计需求和目标设备来定，也有一些常用的分割点，例如：480px、600px、768px、900px、1200px等。</p>
<p>具体语法如下所示：</p>
<p><strong>移动优先</strong></p>
<p>默认的样式为手机的样式</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"> &lt;style&gt;</span><br><span class="line">    body &#123;</span><br><span class="line">        height: 100vh;</span><br><span class="line">        width: 100vw;</span><br><span class="line">        background: red;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @media screen and (min-width: 480px) &#123;</span><br><span class="line">        body &#123;</span><br><span class="line">            background: yellow;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    @media screen and (min-width: 600px) &#123;</span><br><span class="line">        body &#123;</span><br><span class="line">            background: green;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    @media screen and (min-width: 900px) &#123;</span><br><span class="line">        body &#123;</span><br><span class="line">            background: purple;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    @media screen and (min-width: 1200px) &#123;</span><br><span class="line">        body &#123;</span><br><span class="line">            background: palevioletred;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&lt;/style&gt;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p><strong>PC优先</strong></p>
<p>默认的样式为PC屏幕的样式</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">&lt;style&gt;</span><br><span class="line">    body &#123;</span><br><span class="line">        height: 100vh;</span><br><span class="line">        width: 100vw;</span><br><span class="line">        background: red;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @media screen and (min-width: 480px) &#123;</span><br><span class="line">        body &#123;</span><br><span class="line">            background: yellow;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    @media screen and (min-width: 600px) &#123;</span><br><span class="line">        body &#123;</span><br><span class="line">            background: green;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    @media screen and (min-width: 900px) &#123;</span><br><span class="line">        body &#123;</span><br><span class="line">            background: purple;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    @media screen and (min-width: 1200px) &#123;</span><br><span class="line">        body &#123;</span><br><span class="line">            background: palevioletred;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&lt;/style&gt;</span><br></pre></td></tr></table></figure>

<p><img src="/blog/images/post/responsive-html/css-media-type.png" alt="media-type"></p>
<h3 id="弹性布局（rem-x2F-em布局）"><a href="#弹性布局（rem-x2F-em布局）" class="headerlink" title="弹性布局（rem&#x2F;em布局）"></a><strong>弹性布局（rem&#x2F;em布局）</strong></h3><p><strong>1、rem,em区别：</strong>rem,em都是顺应不同网页字体大小展现而产生的。其中，em是相对其父元素，在实际应用中相对而言会带来很多不便；而rem是始终相对于html大小，即页面根元素。</p>
<p>2、使用 em 或 rem 单位进行相对布局，相对%百分比更加灵活，同时可以支持浏览器的字体大小调整和缩放等的正常显示，因为em是相对父级元素的原因没有得到推广。</p>
<p>布局特点：<strong>包裹文字的各元素的尺寸采用em&#x2F;rem做单位，而页面的主要划分区域的尺寸仍使用百分数或px做单位（同「流式布局」或「静态&#x2F;固定布局」）</strong>。<strong>早期浏览器不支持整个页面按比例缩放</strong>，仅支持网页内文字尺寸的放大，这种情况下。使用em&#x2F;rem做单位，可以使包裹文字的元素随着文字的缩放而缩放。</p>
<p>浏览器的默认字体高度一般为<code>16px</code>，即1em:16px，但是 1:16 的比例不方便计算，为了使单位em&#x2F;rem更直观，CSS编写者常常将页面跟节点字体设为62.5%，比如选择用rem控制字体时，先需要设置根节点html的字体大小，因为浏览器默认字体大小16px*62.5%&#x3D;10px。这样1rem便是10px，方便了计算。</p>
<p>因为有些浏览器默认的不是16px，或者用户修改了浏览器默认的字体大小（因浏览器分辨率大小，视力，习惯等因素）。如果我们将其设置为10px，一定会影响在这些浏览器上的效果，所以最好用绝大多数用户默认的16作为基数 * 62.5% 得到我们需要的10px。<em>（关于为什么一般多是 html{font-size:62.5%;} 而不是 html{font-size:10px;}）</em></p>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">html</span> &#123;</span><br><span class="line">	<span class="attribute">font-size</span>: <span class="number">62.5%</span>; <span class="comment">/*10 ÷ 16 × 100% = 62.5% 即： 1rem = 10px */</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="selector-tag">body</span> &#123;</span><br><span class="line">	<span class="attribute">font-size</span>: <span class="number">1.4rem</span>; <span class="comment">/*1.4 × 10px = 14px */</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="selector-tag">h1</span> &#123; </span><br><span class="line">	<span class="attribute">font-size</span>: <span class="number">2.4rem</span>; <span class="comment">/*2.4 × 10px = 24px*/</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p><strong>实际项目设置成 font-size: 62.5%可能会出现问题，因为chrome不支持小于12px的字体，计算小于12px的时候，会默认取12px去计算，导致chrome的em&#x2F;rem计算不准确。</strong></p>
<p><strong>针对这个现象，可以尝试设置html字体为100px，body 修正为16px，这样 0.1rem 就是 10px，而body的字体仍然是默认大小，不影响未设置大小的元素的默认字体的大小。</strong></p>
<p><strong>代码如下：</strong></p>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">html</span> &#123;</span><br><span class="line">	<span class="attribute">font-size</span>: <span class="number">625%</span>; <span class="comment">/* 100 ÷ 16 × 100% = 625%  即 1rem = 100px */</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="selector-tag">body</span> &#123;</span><br><span class="line">	<span class="attribute">font-size</span>: <span class="number">0.16rem</span>; <span class="comment">/* 0.16 × 100 = 16px */</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="相对单位"><a href="#相对单位" class="headerlink" title="相对单位"></a>相对单位</h2><p>相对单位主要用的其实就是px的转换。</p>
<h3 id="rem"><a href="#rem" class="headerlink" title="rem"></a>rem</h3><p>rem是一个相对尺寸，相对于html根元素来进行计算。设置方法查看上面的 <strong>弹性布局（rem&#x2F;em布局）</strong>。</p>
<h3 id="em"><a href="#em" class="headerlink" title="em"></a>em</h3><p>em是相对长度单位，但它取决于父字体大小，也是离它最近的元素的font-size大小。</p>
<h3 id="vw"><a href="#vw" class="headerlink" title="vw"></a>vw</h3><p>是一种视窗单位，也是相对单位，是视窗宽度的百分比的意思。也就是客户端浏览器的可视区域，视窗均分为100个单位，1vw就是视窗宽度的百分之一。</p>
<p>如果需要根据宽度变化来进行百分比调节相关单位，可以自定义一个函数，以scss为例：</p>
<figure class="highlight scss"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">@function</span> rem(<span class="variable">$px</span>) &#123;</span><br><span class="line"> <span class="keyword">@if</span> <span class="variable">$px</span>==<span class="number">0</span> &#123;</span><br><span class="line">  <span class="keyword">@return</span> <span class="number">0</span>;</span><br><span class="line"> &#125;</span><br><span class="line"> <span class="keyword">@else</span> if <span class="variable">$px</span>==<span class="number">1</span> &#123;</span><br><span class="line">  <span class="keyword">@return</span> <span class="number">1px</span>;</span><br><span class="line"> &#125;</span><br><span class="line"> <span class="keyword">@return</span> <span class="variable">$px</span> / <span class="number">375</span> * <span class="number">100vw</span>; <span class="comment">//如果设计图是375，按照宽度为375px进行计算，当设备为375px的时候，1vw=1px</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//具体的样式中使用</span></span><br><span class="line"><span class="selector-class">.test</span>&#123;</span><br><span class="line">    <span class="attribute">font-size</span>: <span class="built_in">rem</span>(<span class="number">16</span>); <span class="comment">//相当于16px</span></span><br><span class="line">    <span class="attribute">width</span>: <span class="built_in">rem</span>(<span class="number">100</span>);</span><br><span class="line">    <span class="attribute">height</span>: <span class="built_in">rem</span>(<span class="number">100</span>); <span class="comment">//以宽高为100px的正方形</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="VH"><a href="#VH" class="headerlink" title="VH"></a>VH</h3><p>和vw一样是视口高度，以百分比方式工作。10vh相当于当前浏览器窗口屏幕高度的10%。</p>
<p>在响应式设计上来说，使用rem更加方便，可以统一更改整个网站的计算。</p>
<h2 id="响应式文字"><a href="#响应式文字" class="headerlink" title="响应式文字"></a>响应式文字</h2><p>响应式文字更改的主要原理还是基于像素单位。</p>
<p>可以使用rem、em、使用vw转换px进行调整文字的大小。</p>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">&lt;style&gt;</span><br><span class="line">    <span class="selector-tag">html</span> &#123;</span><br><span class="line">        <span class="attribute">font-size</span>: <span class="number">625%</span>; //相当于<span class="number">1rem</span>=<span class="number">100px</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="selector-tag">body</span> &#123;</span><br><span class="line">        <span class="attribute">font-size</span>: <span class="number">0.16rem</span>; //<span class="number">16px</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="selector-class">.test</span> &#123;</span><br><span class="line">        <span class="attribute">font-size</span>: <span class="number">0.24rem</span>; //<span class="number">24px</span></span><br><span class="line">    &#125;</span><br><span class="line">&lt;/style&gt;</span><br></pre></td></tr></table></figure>



<h2 id="响应式图片"><a href="#响应式图片" class="headerlink" title="响应式图片"></a>响应式图片</h2><h3 id="万能的100"><a href="#万能的100" class="headerlink" title="万能的100%"></a>万能的100%</h3><figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-class">.image</span>&#123;</span><br><span class="line">    <span class="attribute">max-width</span>: <span class="number">100%</span>;</span><br><span class="line">    <span class="attribute">width</span>: <span class="number">100%</span>;</span><br><span class="line">    <span class="attribute">height</span>: auto;</span><br><span class="line">    <span class="attribute">object-fit</span>: contain;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><img src="/blog/images/post/responsive-html/images.png" alt="百分比的图片"></p>
<p>如上图所示，无论容器根据媒体查询扩张还是缩小，图片都能自适应。当然纵使容器再宽大，图片尺寸也不会超出自己的原生尺寸，等比例缩放，可以解决响应式中的大部分图片适应性问题。</p>
<p>但是如果屏幕过小的情况下，图片中的字就会出现看不清的情况，如上面的图片，右边两张多少还是看的清楚里面的文字的，但是第一张的小屏幕上，已经不太能看得清楚里面具体写了什么，因此需要根据小屏幕更换更加突出重点的图片。也就是根据不同的视口大小、屏幕分辨率等情况下提供不同的图片给用户，如下图所示：</p>
<p><img src="/blog/images/post/responsive-html/big-small.png" alt="左边是手机显示的图片，右边是平板/PC显示的图片"></p>
<h3 id="srcset语法"><a href="#srcset语法" class="headerlink" title="srcset语法"></a>srcset语法</h3><ol>
<li>根据像素比选择相应的图片</li>
</ol>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">img</span> <span class="attr">class</span>=<span class="string">&quot;image&quot;</span> <span class="attr">src</span>=<span class="string">&quot;../source/images/bg/640.jpg&quot;</span> <span class="attr">srcset</span>=<span class="string">&quot;../source/images/bg/641.jpg 2x, ../source/images/bg/642.jpg 1x &quot;</span> <span class="attr">alt</span>=<span class="string">&quot;&quot;</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p><strong>小提示</strong>：上面代码中，2x，1x是像素比，也就是设备像素比(devicePixelRatio，简称dpr)，在js中可以通过window.devicePixelRadio来获取，在css中可以通过-webkit-min-device-pixel-ratio进行检测获取。</p>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">@media</span> <span class="keyword">only</span> screen <span class="keyword">and</span> (<span class="attribute">-webkit-min-device-pixel-ratio</span>: <span class="number">2</span>), </span><br><span class="line">       <span class="keyword">only</span> screen <span class="keyword">and</span> (<span class="attribute">min-device-pixel-ratio</span>: <span class="number">2</span>) &#123;</span><br><span class="line">       <span class="comment">/* CSS styles for devices with dpr of 2 */</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ol start="2">
<li>根据视口大小选择相应的图片</li>
</ol>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">img</span> <span class="attr">class</span>=<span class="string">&quot;image&quot;</span> <span class="attr">src</span>=<span class="string">&quot;big.jpg&quot;</span> <span class="attr">srcset</span>=<span class="string">&quot;big.jpg 1024w, middle.jpg 640w, small.jpg 320w&quot;</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>上面代码是优先PC，默认展示big.jpg，在屏幕大于640px的时候，展示big.jpg；屏幕处于640px~320px的时候，显示middle.jpg；屏幕小于320px的啥时候显示small.jpg。具体的优先展示参考前面的媒体查询的规则。</p>
<ol start="3">
<li>搭配sizes进行使用</li>
</ol>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">img</span> <span class="attr">class</span>=<span class="string">&quot;image&quot;</span> <span class="attr">src</span>=<span class="string">&quot;big.jpg&quot;</span> <span class="attr">srcset</span>=<span class="string">&quot;big.jpg 1024w, middle.jpg 640w, small.jpg 320w&quot;</span> <span class="attr">sizes</span>=<span class="string">&quot;(max-width: 640px) 100vw, (max-width: 960px) 50vw, calc(100vw / 3)&quot;</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>上面代码搭配了sizes，翻译具体的显示逻辑为：当视口宽度不超过640时，图片宽度为视口的100%；当视口宽度大于640但小于960时，图片宽度为视口宽度的50%；当视口宽度大于960时（默认情况），图片宽度为视口的1&#x2F;3。浏览器会根据当前的情况，自主地从提供的图片中选择，给出一个最优的图片。</p>
<h3 id="lt-picture-gt-和-lt-source-gt-元素"><a href="#lt-picture-gt-和-lt-source-gt-元素" class="headerlink" title="&lt;picture&gt;和&lt;source&gt;元素"></a><code>&lt;picture&gt;</code>和<code>&lt;source&gt;</code>元素</h3><p>在响应式图片当中，如果需要基于同一张图片裁剪出多种尺寸的版本。并且针对裁剪后每种尺寸的图片，又要考虑三种用例的情况，将不同尺寸的图片等比例缩放。就需要用到picture和source元素进行展示。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">picture</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">source</span> <span class="attr">media</span>=<span class="string">&quot;(max-width:640px)&quot;</span> <span class="attr">srcset</span>=<span class="string">&quot;small.jpg 320w&quot;</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">source</span> <span class="attr">media</span>=<span class="string">&quot;(max-width:960px)&quot;</span> <span class="attr">srcset</span>=<span class="string">&quot;middle.jpg 640w&quot;</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">source</span> <span class="attr">srcset</span>=<span class="string">&quot;big.jpg 1024w&quot;</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">img</span> <span class="attr">src</span>=<span class="string">&quot;default.jpg&quot;</span> <span class="attr">alt</span>=<span class="string">&quot;&quot;</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">picture</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>如上述代码，浏览器会根据当前的视口去获取相应的图片数据源，展示给用户。<strong>小提示</strong>：必须加上img标签哦~~否则不会展示图片。原因是<code>&lt;source&gt;</code>只为<code>&lt;picture&gt;</code>提供数据源，但是并没有展示的能力，只有选择了恰当的来自<code>&lt;source&gt;</code>的素材并把它加载至<code>&lt;image&gt;</code>上，图片才能显现；另外，当浏览器不支持<code>&lt;picture&gt;</code>的时候，其中的image仍然可以被识别，确保时钟有图片显示在页面上。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">picture</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">source</span> <span class="attr">media</span>=<span class="string">&quot;(max-width:640px)&quot;</span> <span class="attr">srcset</span>=<span class="string">&quot;small.jpg 2x, small-1.jpg 1x &quot;</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">source</span> <span class="attr">media</span>=<span class="string">&quot;(max-width:960px)&quot;</span> <span class="attr">srcset</span>=<span class="string">&quot;middle.jpg 2x, middle-1.jpg 1x&quot;</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">source</span> <span class="attr">srcset</span>=<span class="string">&quot;big.jpg 2x, big-1.jpg 1x&quot;</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">img</span> <span class="attr">class</span>=<span class="string">&quot;image&quot;</span> <span class="attr">src</span>=<span class="string">&quot;default.jpg&quot;</span> <span class="attr">alt</span>=<span class="string">&quot;&quot;</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">picture</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>上述代码获取图片数据源的逻辑为：当视口宽度不超过640时，dpr为2的时候选择small.jpg，dpr为1的时候选择small-1.jpg；当视口宽度大于640但小于960时，，dpr为2的时候选择middle.jpg，dpr为1的时候选择middle-1.jpg；当视口宽度大于960时，dpr为2的时候选择big.jpg，dpr为1的时候选择big-1.jpg。</p>
<p>上述方案实现了多种屏幕视口的情况下，为不同屏幕像素的设备选择更加合适的图片。</p>
<h3 id="放弃图片"><a href="#放弃图片" class="headerlink" title="放弃图片"></a>放弃图片</h3><ol>
<li><strong>使用数据URI</strong></li>
</ol>
<p>通过将图片自身通过Base64编码转化为文本作为元素图片的URI使用。好处是节省了HTTP请求，坏处是，浏览器也无法缓存图片（当页面需要多次引用同一张图片时， 不得不在多出粘贴代码并且占用传输带宽），同时增大了样式文件体积。</p>
<p>设置响应式的时候根据图片的宽高进行合适的显示。</p>
<ol start="2">
<li><strong>使用css形状</strong></li>
</ol>
<p>通过CSS样式属性来把元素模拟为不同的平面几何图形，如圆形、三角形、菱形。</p>
<p>设置响应式的时候使用相对单位即可实现。</p>
<p><img src="/blog/images/post/responsive-html/css-shape.png" alt="css形状"></p>
<ol start="3">
<li><strong>使用图标字体</strong></li>
</ol>
<p>大部分常用的图标使用图标字体，可以设置相应的颜色和形状，简单的可以在<a target="_blank" rel="noopener external nofollow noreferrer" href="https://www.iconfont.cn/?spm=a313x.7781069.1998910419.d4d0a486a">iconfont-阿里巴巴矢量图标库</a>，进行寻找。</p>
<p>使用的时候结合响应式文字以及相对单位进行响应式设置。</p>
<p>由于高清图片体积巨大，能够使用其他方式减少体积尽量使用其他方式。图片性能过程中，对比相应的体积大小，相应来说，图标字体、css是请求文件比较小的方式。也可以对图片进行优化，比如将png-32（位）的图片转化为png-8格式，来进行减少体积。</p>
<p>目前对响应式的理解和实现就暂时到此结束了，后续可能还会有更好的响应式的实现方式，不断学习进步~~</p>
<p><em>附录：</em></p>
<ol>
<li><p><a target="_blank" rel="noopener external nofollow noreferrer" href="https://www.xp.cn/css3/">CSS3参考手册</a></p>
</li>
<li><p><a target="_blank" rel="noopener external nofollow noreferrer" href="https://nc.haut.edu.cn/info/1034/2333.htm">静态布局、自适应布局、流式布局、响应式布局、弹性布局等的概念和区别-河南工业大学信息化管理中心 (haut.edu.cn)</a></p>
</li>
<li><p><a target="_blank" rel="noopener external nofollow noreferrer" href="https://www.cnblogs.com/linxiaoxu/archive/2022/09/22/16720027.html">我的Vue之旅、03 CSS响应式相对单位（em,rem,vw,vh） - 小能日记 - 博客园 (cnblogs.com)</a></p>
</li>
<li><p><a target="_blank" rel="noopener external nofollow noreferrer" href="https://toutiao.io/posts/pnw0as0/preview">【适配】521- 移动端开发各种兼容适配问题（屏幕、图像、字体与布局等） - 开发者头条 (toutiao.io)</a></p>
</li>
</ol>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://lemonxu.eu.org">Lemonxu</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://lemonxu.eu.org/2023/05/31/responsive-html/responsive-html/">https://lemonxu.eu.org/2023/05/31/responsive-html/responsive-html/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow noreferrer" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://lemonxu.eu.org" target="_blank">Lemonxu's Blog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/blog/tags/%E5%89%8D%E7%AB%AF%E5%93%8D%E5%BA%94%E5%BC%8F/">前端响应式</a></div><div class="post_share"><div class="social-share" data-image="/blog/images/bg/641.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/blog/2023/06/16/CSS/CSS/" title="CSS"><img class="cover" src="/blog/images/bg/649.jpg" onerror="onerror=null;src='/blog/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">CSS</div></div></a></div><div class="next-post pull-right"><a href="/blog/2023/05/18/html/html/" title="HTML"><img class="cover" src="/blog/images/bg/649.jpg" onerror="onerror=null;src='/blog/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">HTML</div></div></a></div></nav><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div><div id="comment-switch"><span class="first-comment">Valine</span><span class="switch-btn"></span><span class="second-comment">Disqus</span></div></div><div class="comment-wrap"><div><div class="vcomment" id="vcomment"></div></div><div><div id="disqus_thread"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/blog/images/user.jpg" onerror="this.onerror=null;this.src='/blog/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">Lemonxu</div><div class="author-info__description">一个以前端开发为主的博客，一个专注前端的开发人员</div></div><div class="card-info-data site-data is-center"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">4</div></a><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">4</div></a><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">8</div></a></div><a id="card-info-btn" target="_blank" rel="noopener external nofollow noreferrer" href="https://github.com/Lemonxu"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/Lemonxu" rel="external nofollow noreferrer" target="_blank" title="Github"><i class="fab fa-github" style="color: #24292e;"></i></a><a class="social-icon" href="mailto:yunfeng7@foxmail.com" rel="external nofollow noreferrer" target="_blank" title="Email"><i class="fas fa-envelope" style="color: #4a7dbe;"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%B8%BA%E4%BB%80%E4%B9%88%E9%9C%80%E8%A6%81%E8%AE%BE%E8%AE%A1%E5%93%8D%E5%BA%94%E5%BC%8F%E8%AE%BE%E8%AE%A1"><span class="toc-number">1.</span> <span class="toc-text">为什么需要设计响应式设计</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%93%8D%E5%BA%94%E5%BC%8F%E8%AE%BE%E8%AE%A1%E5%AE%9E%E7%8E%B0%E6%96%B9%E6%A1%88"><span class="toc-number">2.</span> <span class="toc-text">响应式设计实现方案</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%A1%B5%E9%9D%A2%E5%B8%83%E5%B1%80"><span class="toc-number">2.1.</span> <span class="toc-text">页面布局</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%9D%99%E6%80%81%E5%B8%83%E5%B1%80"><span class="toc-number">2.1.1.</span> <span class="toc-text">静态布局</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B5%81%E5%BC%8F%E5%B8%83%E5%B1%80"><span class="toc-number">2.1.2.</span> <span class="toc-text">流式布局</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%87%AA%E9%80%82%E5%BA%94%E5%B8%83%E5%B1%80"><span class="toc-number">2.1.3.</span> <span class="toc-text">自适应布局</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%93%8D%E5%BA%94%E5%BC%8F%E5%B8%83%E5%B1%80"><span class="toc-number">2.1.4.</span> <span class="toc-text">响应式布局</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AA%92%E4%BD%93%E6%9F%A5%E8%AF%A2"><span class="toc-number">2.1.4.1.</span> <span class="toc-text">媒体查询</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%BC%B9%E6%80%A7%E5%B8%83%E5%B1%80%EF%BC%88rem-x2F-em%E5%B8%83%E5%B1%80%EF%BC%89"><span class="toc-number">2.1.5.</span> <span class="toc-text">弹性布局（rem&#x2F;em布局）</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%9B%B8%E5%AF%B9%E5%8D%95%E4%BD%8D"><span class="toc-number">2.2.</span> <span class="toc-text">相对单位</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#rem"><span class="toc-number">2.2.1.</span> <span class="toc-text">rem</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#em"><span class="toc-number">2.2.2.</span> <span class="toc-text">em</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#vw"><span class="toc-number">2.2.3.</span> <span class="toc-text">vw</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#VH"><span class="toc-number">2.2.4.</span> <span class="toc-text">VH</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%93%8D%E5%BA%94%E5%BC%8F%E6%96%87%E5%AD%97"><span class="toc-number">2.3.</span> <span class="toc-text">响应式文字</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%93%8D%E5%BA%94%E5%BC%8F%E5%9B%BE%E7%89%87"><span class="toc-number">2.4.</span> <span class="toc-text">响应式图片</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%87%E8%83%BD%E7%9A%84100"><span class="toc-number">2.4.1.</span> <span class="toc-text">万能的100%</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#srcset%E8%AF%AD%E6%B3%95"><span class="toc-number">2.4.2.</span> <span class="toc-text">srcset语法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#lt-picture-gt-%E5%92%8C-lt-source-gt-%E5%85%83%E7%B4%A0"><span class="toc-number">2.4.3.</span> <span class="toc-text">&lt;picture&gt;和&lt;source&gt;元素</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%94%BE%E5%BC%83%E5%9B%BE%E7%89%87"><span class="toc-number">2.4.4.</span> <span class="toc-text">放弃图片</span></a></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/blog/2023/06/25/javascript/" title="javascript"><img src="/blog/images/bg/646.jpg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="javascript"/></a><div class="content"><a class="title" href="/blog/2023/06/25/javascript/" title="javascript">javascript</a><time datetime="2023-06-25T09:39:57.000Z" title="发表于 2023-06-25 17:39:57">2023-06-25</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2023/06/16/CSS/CSS/" title="CSS"><img src="/blog/images/bg/649.jpg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="CSS"/></a><div class="content"><a class="title" href="/blog/2023/06/16/CSS/CSS/" title="CSS">CSS</a><time datetime="2023-06-16T03:57:58.000Z" title="发表于 2023-06-16 11:57:58">2023-06-16</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2023/05/31/responsive-html/responsive-html/" title="前端响应式网站设计"><img src="/blog/images/bg/641.jpg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="前端响应式网站设计"/></a><div class="content"><a class="title" href="/blog/2023/05/31/responsive-html/responsive-html/" title="前端响应式网站设计">前端响应式网站设计</a><time datetime="2023-05-31T01:07:50.000Z" title="发表于 2023-05-31 09:07:50">2023-05-31</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2023/05/18/html/html/" title="HTML"><img src="/blog/images/bg/649.jpg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="HTML"/></a><div class="content"><a class="title" href="/blog/2023/05/18/html/html/" title="HTML">HTML</a><time datetime="2023-05-18T03:46:54.000Z" title="发表于 2023-05-18 11:46:54">2023-05-18</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2023 By Lemonxu</div><div class="footer_custom_text">本博客由Lemonxu使用Hexo搭建，部分素材来自网络，如有侵权请联系删除</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="chat_btn" type="button" title="聊天"><i class="fas fa-sms"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/blog/js/utils.js"></script><script src="/blog/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><div class="js-pjax"><script>function loadValine () {
  function initValine () {
    const valine = new Valine(Object.assign({
      el: '#vcomment',
      appId: '',
      appKey: '',
      avatar: 'monsterid',
      serverURLs: '',
      emojiMaps: "",
      path: window.location.pathname,
      visitor: false
    }, null))
  }

  if (typeof Valine === 'function') initValine() 
  else getScript('https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js').then(initValine)
}

if ('Valine' === 'Valine' || !true) {
  if (true) btf.loadComment(document.getElementById('vcomment'),loadValine)
  else setTimeout(loadValine, 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script><script>function loadDisqus () {
  const disqus_config = function () {
    this.page.url = 'https://lemonxu.eu.org/2023/05/31/responsive-html/responsive-html/'
    this.page.identifier = '/blog/2023/05/31/responsive-html/responsive-html/'
    this.page.title = '前端响应式网站设计'
  }

  const disqusReset = () => {
    DISQUS.reset({
      reload: true,
      config: disqus_config
    })
  }

  btf.addModeChange('disqus', disqusReset)

  if (window.DISQUS) disqusReset()
  else {
    (function() { 
      var d = document, s = d.createElement('script');
      s.src = 'https://.disqus.com/embed.js';
      s.setAttribute('data-timestamp', +new Date());
      (d.head || d.body).appendChild(s);
    })();
  }
}

if ('Valine' === 'Disqus' || !true) {
  if (true) btf.loadComment(document.getElementById('disqus_thread'), loadDisqus)
  else loadDisqus()
} else {
  function loadOtherComment () {
    loadDisqus()
  }
}
</script></div><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-fluttering-ribbon.min.js"></script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>let pjaxSelectors = ["head > title","#config-diff","#body-wrap","#rightside-config-hide","#rightside-config-show",".js-pjax"]

var pjax = new Pjax({
  elements: 'a:not([target="_blank"]):not([href="/music/"]):not([href="/no-pjax/"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.tocScrollFn && window.removeEventListener('scroll', window.tocScrollFn)
  window.scrollCollect && window.removeEventListener('scroll', scrollCollect)

  document.getElementById('rightside').style.cssText = "opacity: ''; transform: ''"
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

  typeof disqusjs === 'object' && disqusjs.destroy()
})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>